package com.huawei.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huawei.common.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author LF
 * projectName:vue-cli
 * description:
 * time:2025-04-29 23:13
 */
@Component
public class ValidateCaptchaFilter extends OncePerRequestFilter {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        //处理乱码问题
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String requestURI = request.getRequestURI();
        //对登录、获取验证码、退出登录放行
        if (requestURI.endsWith("/login")) {
            //是登陆请求，校验验证码
            if (requestURI.endsWith("/login")) {
                String code = request.getParameter("code");
                code = code == null ? "" : code;
                String uuid = request.getParameter("uuid");
                String captcha = stringRedisTemplate.opsForValue().get("captcha:" + uuid);
                if (!code.equalsIgnoreCase(captcha)) {
                    BaseResult result = new BaseResult(-1, "验证码错误");
                    response.getWriter().write(objectMapper.writeValueAsString(result));
                    return;
                }
            }
            //验证码正确放行
            filterChain.doFilter(request, response);
            return;
        }
        filterChain.doFilter(request, response);
    }
}
